import nprogress from 'nprogress'
import '@/styles/nprogress.scss'
import router from '@/router'
import pinia from '@/store'
import useUserStore from '@/store/modules/user/user'
import Setting from '@/setting'

// 关闭加载动画
nprogress.configure({ showSpinner: false })

//使用小仓库前提是必须有大仓库,需要传入pinia
let userStore = useUserStore(pinia)

//路由守卫
//前置守卫
router.beforeEach(async (to: any, from: any, next: any) => {
  nprogress.start()
  let token = userStore.token
  if (token) {
    // 已经登录
    // 查询是否有用户信息
    let userInfo = userStore.userInfo
    if (userInfo) {
      //包含用户信息
      if (to.path == '/login') {
        //已经登录用户不允许访问登录页 跳转到登录页
        next({ path: '/home' })
      } else {
        next()
      }
    } else {
      try {
        //不含用户信息 发送请求
        await userStore.getUserInfo()
        next()
      } catch (e) {
        // 登录失败
        // 跳转到登录页
        next({ path: '/login', query: 'redirect' + to.path })
      }
    }
  } else {
    //未登录 跳转到登录页
    if (to.path === '/login') {
      next()
    } else {
      next({ path: '/login' })
    }
  }
})
//路由离开守卫
router.afterEach((to: any, from: any) => {
  document.title = `${Setting.title} - ${to.meta.title}`
  nprogress.done()
})
